package entity

import (
	"fmt"
	"database/sql/driver"
	"time"
	"github.com/lib/pq"
	"strconv"
)

type Time struct {
	time.Time
}

func (a *Time) Scan(src interface{}) error {
	switch src := src.(type) {
	case time.Time:
		a.Time = src
		return nil
	}
	return fmt.Errorf("pq: cannot convert %T to Time", src)
}

func (a Time) Value() (driver.Value, error) {
	return string(pq.FormatTimestamp(a.Time)), nil
}

// customized json format

func (t *Time) UnmarshalJSON(data []byte) (err error) {
	ts, err := strconv.ParseInt(string(data), 10, 64)
	if err != nil {
		return err
	}
	t.Time = time.Unix(ts>>32, (ts<<32)>>32)
	return
}

func (t Time) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprint(t.Unix())), nil
}
